package caculate.linkedList;

/**
 * 合并两个有序数组，最终返回还是有序数组
 *
 * @program: rocsun
 * @description:
 * @author: yx.guo
 * @create: 2025-04-14 19:34
 **/
public class MergeTwoLists {

    public static void main(String[] args) {
        ListNode list1 = new ListNode(1, new ListNode(2, new ListNode(4, null)));
        ListNode list2 = new ListNode(1, new ListNode(3, new ListNode(4, null)));
        ListNode listNode = mergeTwoLists(list1, list2);
        System.out.println();
    }

    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null || list2 == null) {
            return list1 == null ? list2 : list1;
        }

        ListNode node1 = list1;
        ListNode node2 = list2;

        ListNode head = new ListNode(0, null);
        ListNode tail = head;
        while (node1 != null && node2 != null) {
            ListNode node;
            if (node1.val < node2.val) {
                node = node1;
                node1 = node1.next;
            } else {
                node = node2;
                node2 = node2.next;
            }
            node.next = null; // 断开下一节点的连接
            tail.next = node; // 拼到新链表
            tail = node; // 为节点指向新的尾节点
        }

        if (node1 != null) {
            tail.next = node1;
        }

        if (node2 != null) {
            tail.next = node2;
        }

        return head.next;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

}
